/**
 * Created by 袁奎 on 2017/6/23.
 * 主要是一些平时js中经常使用的一些方法进行封装
 * 包括跳转、获取定位、cookie操作等
 */

(function ($) {
    $.extend({

        /**
         * console.log方法简写
         * @param message
         */
        log: function (message) {
            console.log(message);
        },

        /**
         * 展示信息
         * @param msg
         * @param errorBack
         */
        showInfo: function (msg, errorBack) {
            try {
                document.write(msg);
            } catch (e) {
                if (errorBack) {
                    errorBack(e.message);
                } else {
                    $.log(e.message);
                }
            }
        },

        /**
         * 跳转
         * @param url
         */
        jump: function (url) {
            if (url.indexOf('?') >= 0) {
                window.location.href = url + '&_v=' + Math.random();
            } else {
                window.location.href = url + '?_v=' + Math.random();
            }
        },

        /**
         * 文本框限制【1=>只允许数字 2=>只允许字母 3=>只允许汉字 4=>只允许字母和数字】
         * @param obj
         * @param tag
         */
        inputLimit: function (obj, tag, scense) {
            var attr = "onblur";
            if (scense === 1) {
                attr = "onkeyup";
            }
            switch (tag) {
                case 1:
                    obj.attr(attr, "this.value=this.value.replace(/\\D/g,'')");
                    break;
                case 2:
                    obj.attr(attr, "this.value=this.value.replace(/[^a-zA-Z]/g,'')");
                    break;
                case 3:
                    obj.attr(attr, "this.value=this.value.replace(/[^\\u4E00-\\u9FA5]/g,'')");
                    break;
                case 4:
                    obj.attr(attr, "this.value=(/^[a-zA-Z0-9]+$/g.test(this.value))?this.value:this.value.replace(this.value,'')");
                    break;
            }
        },

        /**
         * 定位
         * @param callBack
         */
        getPosition: function (callBack) {
            if (navigator.geolocation) {
                try {
                    navigator.geolocation.getCurrentPosition(function (position) {
                        callBack(position.coords.latitude, position.coords.longitude);
                    });
                } catch (e) {
                    callBack('', '', e.message);
                }
            } else {
                $.log('定位失败');
            }
        },

        /**
         * 下拉执行
         * @param obj
         * @param yourFunc
         */
        dropDown: function (obj, yourFunc) {
            try {
                $(window).scroll(function () {
                    if (($(document).height() - obj.scrollTop() - obj.height()) < 20) {
                        yourFunc();
                    }
                });
            } catch (e) {
                yourFunc(e.message);
            }
        },

        /****************************Cookie的相关操作****************************/
        /**
         * 写cookie
         * @param key
         * @param value
         * @param overdueTime
         */
        writeCookie: function (key, value, overdueTime, cookie_domain, cookie_path) {
            var exp = new Date();
            exp.setTime(exp.getTime() + overdueTime * 1000);
            document.cookie = key + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";domain=" + cookie_domain + ";path=" + cookie_path;
        },

        /**
         * 获取cookie
         * @param key
         * @param value
         * @param overdueTime
         */
        gainCookie: function (key) {
            var arr, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg)) {
                return unescape(arr[2]);
            } else {
                return null;
            }
        },

        /**
         * 删除cookie
         * @param key
         * @param value
         * @param overdueTime
         */
        delCookie: function (key, cookie_domain, cookie_path) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var value = '';
            document.cookie = key + "=" + value + ";expires=" + exp.toGMTString() + ";domain=" + cookie_domain + ";path=" + cookie_path;
        },
        /*******************************end Cookie ****************************/

        /****************************String 相关操作***************************/

        /**
         * 字符串全部替换
         * @param s1
         * @param s2
         */
        allSubstitute: function (str, s1, s2) {
            return str.replace(new RegExp(s1, "gm"), s2);
        },

        /**
         * 去除所有空格
         * @param str
         */
        trimAll: function (str) {
            return str.replace(/\s+/g, '');
        },

        /**
         * 是否是邮箱
         * @param emailStr
         * @returns {boolean}
         */
        is_email: function (emailStr) {
            if (emailStr.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) return true;
            return false;
        },

        /**
         * 格式化时间
         * 年：yyyy 月：MM 日：dd 小时：hh 分钟：mm 秒：ss 毫秒：SS 星期：w 季度：q
         * @param format
         * @param date
         * @returns {*}
         */
        formatData: function (format, date) {
            if (!date) {
                date = new Date();
            }
            var Weeks = ['日', '一', '二', '三', '四', '五', '六'];
            var options = {
                "y+": date.getYear(),
                "M+": date.getMonth() + 1,
                "d+": date.getDate(),
                "h+": date.getHours(),
                "H+": date.getHours(),
                "m+": date.getMinutes(),
                "s+": date.getSeconds(),
                "q+": Math.floor((date.getMonth() + 3) / 3),
                "S": date.getMilliseconds(),
                "w": Weeks[date.getDay()]
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in options) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? options[k] : ("00" + options[k]).substr(("" + options[k]).length));
                }
            }
            return format;
        },

        /**
         * 格式化数字
         * @param number 要格式化的数字
         * @param decimals 保留几位小数
         * @returns {string}
         */
        formatNumber: function (number, decimals) {
            var wait_format_number = number.split('.');
            var dec_str = '';
            if (typeof wait_format_number[1] !== 'undefined') {
                dec_str = wait_format_number[1].substr(0, decimals);
                var final_num = parseInt(dec_str.substr(dec_str.length));
                if (final_num > 5) {
                    final_num = parseInt(dec_str) + 1;
                } else {
                    final_num = parseInt(dec_str);
                }
                return wait_format_number[0] + '.' + final_num;
            } else if (typeof wait_format_number[1] === 'undefined' || wait_format_number[1] === '') {
                for (var i = 0; i < decimals; i++) {
                    dec_str += '0';
                }
                return wait_format_number[0] + '.' + dec_str;
            }
        },

        /**
         * 获取一个拼接时间戳的唯一ID
         * @returns {string}
         */
        getUniqueId: function () {
            var a = Math.random, b = parseInt;
            return Number(new Date()).toString() + b(10 * a()) + b(10 * a()) + b(10 * a());
        },

        /**
         * 获取所有url参数
         * @returns {Array}
         */
        getUrlParams: function () {
            var url = location.href;
            var returnArray = new Array();
            if (url.indexOf('?') < 0) return returnArray;
            var paramStr = url.substr(url.indexOf('?') + 1);
            var paramStrArray = paramStr.split('&');
            var forLength = paramStrArray.length;
            var tempstr = '';
            for (var i = 0; i < forLength; i++) {
                if (paramStrArray[i].indexOf('=') > 0) {
                    tempstr = paramStrArray[i].split('=');
                    returnArray[tempstr[0]] = tempstr[1];
                }
            }
            return returnArray;
        },

        /******************************end String*****************************/

        /******************************start Array*****************************/

        /**
         * 某元素是否在数组中
         * @param array
         * @param param
         * @returns {boolean}
         */
        in_array: function (array, param) {
            var temp_length = array.length;
            for (var i = 0; i < temp_length; i++) {
                if (array[i] === param)
                    return true;
            }
            return false;
        },

        /**
         * 返回元素在数组中的位置
         * @param array
         * @param param
         * @returns {number}
         */
        elementPosition: function (array, param) {
            var temp_length = array.length;
            for (var i = 0; i < temp_length; i++) {
                if (array[i] === param)
                    return i;
            }
            return -1;
        },

        /******************************end Array******************************/

        /**
         * ajax请求封装
         * @param url
         * @param type
         * @param dataType
         * @param data
         * @param successBack
         * @param completeBack
         * @param errorBack
         * @param bsFunc
         * @param contentType
         */
        doAjaxRequest: function (url, type, dataType, data, successBack, completeBack, errorBack, bsFunc, contentType) {
            if (type === '') type = 'get';
            if (dataType === '') type = 'json';
            if (data === '') data = {};
            if (contentType === '') contentType = 'application/x-www-form-urlencoded';
            var ajax = $.ajax(url, {
                type: type,
                dataType: dataType,
                data: data,
                contentType: contentType,
                beforeSend: function () {
                    if (bsFunc) bsFunc();
                }
            });
            if (successBack) {
                ajax.done(function (data) {
                    successBack(data);
                });
            }
            if (completeBack) {
                ajax.always(function (data) {
                    completeBack(data);
                });
            }
            if (errorBack) {
                ajax.fail(function (data) {
                    errorBack(data);
                });
            }
        }
    });
})(jQuery);